<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>记事本</title>
		<style>
			/* 基础重置：统一浏览器默认样式 */
			* {
				margin: 0;
				padding: 0;
				box-sizing: border-box;
			}
			body {
				font-family: "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
				background-color: #f8f9fa;
				color: #333;
				line-height: 1.6;
				padding: 20px 15px;
			}

			/* 容器样式：居中+卡片质感 */
			#bodyPart {
				max-width: 1200px;
				margin: 0 auto;
				background-color: #fff;
				border-radius: 12px;
				box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
				padding: 30px;
				overflow: hidden;
			}

			/* 标题样式：强化视觉焦点 */
			h1 {
				color: #2d3748;
				font-size: 24px;
				font-weight: 600;
				margin-bottom: 25px;
				padding-bottom: 12px;
				border-bottom: 1px solid #f0f2f5;
				display: flex;
				align-items: center;
			}
			h1::before {
				content: "";
				display: inline-block;
				width: 4px;
				height: 24px;
				background-color: #409eff;
				border-radius: 2px;
				margin-right: 12px;
			}

			/* 顶部按钮组：优化间距与质感 */
			.top-btn-group {
				margin-bottom: 25px;
			}
			.top-btn-group button {
				display: inline-flex;
				align-items: center;
				justify-content: center;
				padding: 10px 22px;
				background-color: #409eff;
				color: #fff;
				border: none;
				border-radius: 6px;
				cursor: pointer;
				font-size: 14px;
				font-weight: 500;
				transition: all 0.3s ease;
				box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
			}
			.top-btn-group button:hover {
				background-color: #3086e8;
				box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
				transform: translateY(-1px);
			}
			.top-btn-group button i {
				margin-right: 8px;
				font-size: 16px;
			}

			/* 列表容器：统一间距 */
			#eventList {
				list-style: none;
				margin: 0;
				padding: 0;
			}

			/* 列表项：卡片化+hover动效 */
			#eventList li {
				background-color: #fff;
				border: 1px solid #f0f2f5;
				border-radius: 8px;
				padding: 25px;
				margin-bottom: 18px;
				transition: all 0.3s ease;
				position: relative;
				overflow: hidden;
			}
			#eventList li:hover {
				border-color: #e1e5eb;
				box-shadow: 0 6px 16px rgba(0, 0, 0, 0.04);
				transform: translateY(-2px);
			}

			/* 操作按钮组：右上角悬浮+图标优化 */
			.action-btns {
				position: absolute;
				top: 20px;
				right: 20px;
				display: flex;
				gap: 10px;
				z-index: 1;
			}
			.action-btns button {
				display: inline-flex;
				align-items: center;
				justify-content: center;
				padding: 7px 14px;
				border: none;
				border-radius: 6px;
				cursor: pointer;
				font-size: 13px;
				font-weight: 500;
				transition: all 0.3s ease;
				gap: 6px;
			}
			/* 修改按钮：暖色调+图标 */
			.edit-btn {
				background-color: #fff7e6;
				color: #e6a23c;
				border: 1px solid #ffe8b4;
			}
			.edit-btn:hover {
				background-color: #fff0cc;
				border-color: #ffd591;
			}
			/* 删除按钮：红色调+图标 */
			.delete-btn {
				background-color: #fff2f0;
				color: #f56c6c;
				border: 1px solid #ffd2d2;
			}
			.delete-btn:hover {
				background-color: #ffe6e6;
				border-color: #ffbbbb;
			}

			/* 数据展示区：网格布局+对齐优化 */
			.event-data {
				display: grid;
				grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
				gap: 16px;
				margin-top: 10px;
			}
			.items {
				display: flex;
				align-items: flex-start;
				font-size: 14px;
			}
			.items label {
				width: 70px;
				color: #6e7781;
				font-weight: 500;
				flex-shrink: 0;
			}
			.items span {
				color: #2d3748;
				flex: 1;
				word-break: break-all;
				padding-right: 10px;
			}
			/* 特殊字段高亮：ID和金额 */
			.items.id-item span {
				color: #409eff;
				font-family: "Courier New", monospace;
				font-size: 13px;
			}
			.items.money-item span {
				color: #e6a23c;
				font-weight: 500;
			}

			/* 加载/错误/空数据：统一卡片样式 */
			.status-card {
				padding: 30px;
				text-align: center;
				border-radius: 8px;
				margin-bottom: 20px;
				font-size: 15px;
			}
			.loading {
				background-color: #f0f7ff;
				color: #409eff;
				border: 1px solid #e6f7ff;
			}
			.error {
				background-color: #fff1f0;
				color: #f56c6c;
				border: 1px solid #fff1f0;
				display: none;
			}
			.empty-data {
				background-color: #f9fafb;
				color: #9ca3af;
				border: 1px dashed #e5e7eb;
			}
			.empty-data i {
				font-size: 24px;
				margin-bottom: 12px;
				color: #d1d5db;
			}

			/* 删除确认弹窗：居中+毛玻璃效果 */
			.confirm-modal {
				position: fixed;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				background-color: rgba(0, 0, 0, 0.5);
				backdrop-filter: blur(4px);
				display: flex;
				align-items: center;
				justify-content: center;
				z-index: 1000;
				opacity: 0;
				visibility: hidden;
				transition: all 0.3s ease;
			}
			.confirm-modal.show {
				opacity: 1;
				visibility: visible;
			}
			.modal-content {
				background-color: #fff;
				width: 90%;
				max-width: 420px;
				border-radius: 10px;
				padding: 30px;
				box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
				transform: translateY(20px);
				transition: transform 0.3s ease;
			}
			.confirm-modal.show .modal-content {
				transform: translateY(0);
			}
			.modal-content h3 {
				margin-top: 0;
				color: #2d3748;
				font-size: 16px;
				font-weight: 600;
				margin-bottom: 20px;
				display: flex;
				align-items: center;
			}
			.modal-content h3 i {
				color: #f56c6c;
				margin-right: 10px;
				font-size: 18px;
			}
			.modal-btn-group {
				display: flex;
				justify-content: flex-end;
				gap: 12px;
				margin-top: 25px;
			}
			.modal-btn-group button {
				padding: 9px 20px;
				border-radius: 6px;
				border: none;
				cursor: pointer;
				font-size: 14px;
				font-weight: 500;
				transition: all 0.3s ease;
			}
			.cancel-btn {
				background-color: #f9fafb;
				color: #6b7280;
				border: 1px solid #e5e7eb;
			}
			.cancel-btn:hover {
				background-color: #f3f4f6;
			}
			.confirm-btn {
				background-color: #f56c6c;
				color: #fff;
			}
			.confirm-btn:hover {
				background-color: #e4393c;
			}

			/* 响应式适配：移动端优化 */
			@media (max-width: 768px) {
				#bodyPart {
					padding: 20px 15px;
				}
				h1 {
					font-size: 20px;
				}
				.action-btns {
					top: 15px;
					right: 15px;
				}
				.action-btns button {
					padding: 6px 10px;
					font-size: 12px;
				}
				.event-data {
					grid-template-columns: 1fr; /* 移动端单列布局 */
					gap: 12px;
				}
				.items {
					align-items: center;
				}
				.items label {
					width: 60px;
					font-size: 13px;
				}
				.items span {
					font-size: 13px;
				}
				.modal-content {
					padding: 25px 20px;
				}
			}
		</style>
		<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
	</head>
	<body>
		<div id="bodyPart">
			<h1>事项列表</h1>

			<!-- 顶部按钮组 -->
			<div class="top-btn-group">
				<button onclick="window.location.href='/eventform.html'">
					<i class="fa fa-plus-circle"></i> 创建事项
				</button>
			</div>

			<!-- 状态提示卡片 -->
			<div class="status-card loading" id="loading">
				<i class="fa fa-spinner fa-spin"></i> 正在加载事项数据...
			</div>
			<div class="status-card error" id="error"></div>

			<!-- 事项列表容器 -->
			<ul id="eventList"></ul>
		</div>

		<!-- 删除确认弹窗 -->
		<div class="confirm-modal" id="deleteModal">
			<div class="modal-content">
				<h3><i class="fa fa-exclamation-circle"></i> 确认删除该事项吗？</h3>
				<p>删除后数据将不可恢复，请谨慎操作！</p>
				<div class="modal-btn-group">
					<button class="cancel-btn" onclick="hideDeleteModal()">取消</button>
					<button class="confirm-btn" onclick="confirmDelete()">
						确认删除
					</button>
				</div>
			</div>
		</div>

		<script>
			let pendingDeleteId = "";
			window.addEventListener("DOMContentLoaded", async () => {
				try {
					// ② 发 GET 请求
					// 从 localStorage 获取 token
					const token = localStorage.getItem("token");

					if (!token) {
						// 如果没有 token，跳转到登录页
						alert("请先登录！");
						window.location.href = "/login.html"; // 假设你的登录页叫 login.html
						return;
					}

					// 发送带 token 的请求
					const res = await axios.get("/api/event", {
						headers: {
							Authorization: `Bearer ${token}`,
						},
					});
					const data = res.data.data;

					const loadingElem = document.querySelector("#loading");
					const errorElem = document.querySelector("#error");
					const eventListElem = document.querySelector("#eventList");

					loadingElem.style.display = "none";

					if (data.length === 0) {
						eventListElem.innerHTML = `
                        <div class="empty-data">
                            暂无事项数据，点击"创建"按钮添加新事项吧！
                        </div>
                    `;
						return;
					}

					let listHtml = "";
					data.forEach((event) => {
						//id格式化
						const eventId = event._id ? String(event._id) : "未知ID";

						//时间格式化
						const formattedTime = event.eventtime
							? new Date(event.eventtime).toLocaleString("zh-CN", {
									year: "numeric",
									month: "2-digit",
									day: "2-digit",
									hour: "2-digit",
									minute: "2-digit",
									second: "2-digit",
									timeZone: "Asia/Shanghai",
							  })
							: "未设置";

						//金额格式化
						const formattedMoney = event.eventmoney
							? Number(event.eventmoney).toFixed(2)
							: "0.00";

						listHtml += `
                        <li>
                            <!-- 修改/删除按钮组（右上角） -->
                            <div class="action-btns">
                                <!-- 修改按钮：跳转到修改页，携带当前事项ID -->
                                <button class="edit-btn" onclick="goToEditPage('${eventId}')">修改</button>
                                <!-- 删除按钮：显示确认弹窗 -->
                                <button class="delete-btn" onclick="showDeleteModal('${eventId}')">删除</button>
                            </div>

                            <!-- 事项数据展示（与之前一致） -->
                            <div class="items">
                                <label for="eventID-${eventId}">ID：</label>
                                <span id="eventID-${eventId}">${eventId}</span>
                            </div>
                            <div class="items">
                                <label for="eventName-${eventId}">事项：</label>
                                <span id="eventName-${eventId}">${
							event.eventname || "未命名"
						}</span>
                            </div>
                            <div class="items">
                                <label for="eventTime-${eventId}">时间：</label>
                                <span id="eventTime-${eventId}">${formattedTime}</span>
                            </div>
                            <div class="items">
                                <label for="eventMoney-${eventId}">金额：</label>
                                <span id="eventMoney-${eventId}">${formattedMoney}￥</span>
                            </div>
                            <div class="items">
                                <label for="eventType-${eventId}">类型：</label>
                                <span id="eventType-${eventId}">${
							event.eventtype || "未分类"
						}</span>
                            </div>
                            <div class="items">
                                <label for="eventNote-${eventId}">备注：</label>
                                <span id="eventnote-${eventId}">${
							event.eventnote || "无"
						}</span>
                            </div>
                        </li>
                    `;

						eventListElem.innerHTML = listHtml;
					});
				} catch (err) {
					console.log(err);

					alert("拉取数据失败：" + err.message);
				}

				/**
				 * 跳转到修改页（携带事项ID）
				 * @param {string} eventId - 待修改事项的ID
				 */
				function goToEditPage(eventId) {
					// 跳转到 edit.html，并通过URL参数传递ID（后续修改页需通过此ID获取原数据）
					window.location.href = `/edit.html?id=${eventId}`;
				}

				// ---------------------- 新增功能：删除相关 ----------------------
				/**
				 * 显示删除确认弹窗
				 * @param {string} eventId - 待删除事项的ID
				 */
				function showDeleteModal(eventId) {
					pendingDeleteId = eventId; // 存储待删除ID
					document.getElementById("deleteModal").style.display = "flex"; // 显示弹窗
				}

				/**
				 * 隐藏删除确认弹窗
				 */
				function hideDeleteModal() {
					pendingDeleteId = ""; // 清空待删除ID
					document.getElementById("deleteModal").style.display = "none"; // 隐藏弹窗
				}

				/**
				 * 确认删除（发送请求到后端删除数据库数据）
				 */
				async function confirmDelete() {
					if (!pendingDeleteId) return; // 防止无ID删除

					try {
						// 发送DELETE请求到后端（需后端配合实现删除接口）
						const token = localStorage.getItem("token");
						if (!token) {
							alert("登录已过期，请重新登录！");
							window.location.href = "/login.html";
							return;
						}

						const response = await axios.delete(
							`/api/events/${pendingDeleteId}`,
							{
								headers: {
									Authorization: `Bearer ${token}`,
								},
							}
						);

						if (response.data.success) {
							// 删除成功：刷新页面重新渲染数据
							window.location.reload();
						} else {
							throw new Error(response.data.message || "删除失败");
						}
					} catch (err) {
						// 删除失败：提示用户
						alert(`删除失败：${err.message || "网络异常，请重试"}`);
						console.error("删除错误：", err);
						hideDeleteModal(); // 隐藏弹窗
					}
				}
			});
		</script>
	</body>
</html>
